package com.danger.Activity.Account;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.danger.Activity.BackHandledFragment;
import com.danger.Activity.R;
import com.danger.Model.bean.UserInfoBean;
import com.danger.Presenter.UserInfoPresenter;
import com.danger.Presenter.UserInfoPresenterImpl;
import com.danger.Util.FileCacheService;
import com.danger.Util.ImageUtil.ImageLoaderUtil;
import com.danger.View.CommonView;
import com.danger.Widget.MyCircleImageView;
import com.nostra13.universalimageloader.core.assist.ImageSize;

import cn.bmob.v3.BmobUser;

/**
 * Created by danger on 2016/4/26.
 */
public class ModifyPhotoFragment extends BackHandledFragment implements CommonView, View.OnClickListener {

    private boolean hadIntercept;
    private View view;
    private String url;
    private String photo;
    private UserInfoActivity activity;
    private Toolbar toolbar;
    private ProgressDialog dialog;
    private MyCircleImageView register_photo;
    private Button choose_photo;
    private Button upload_photo;
    private UserInfoPresenter presenter;
    private UserInfoBean userInfo;
    private FileCacheService service;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_upload_photo, container, false);

        initView();
        initEvent();

        return view;
    }

    private void initView() {
        activity = (UserInfoActivity) getActivity();
        toolbar = activity.getToolbar();
        toolbar.setTitle("修改头像");
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        service = new FileCacheService(activity);
        register_photo = (MyCircleImageView) view.findViewById(R.id.register_photo);
        userInfo = BmobUser.getCurrentUser(activity, UserInfoBean.class);
        if (service.getSharePreference("setting").get("theme").equals("2")) {
            activity.getUserNameTexTView().setText(userInfo.getUsername().toString());
            activity.getUserPhoneTextView().setText(userInfo.getMobilePhoneNumber().toString());
            if (userInfo.getPhoto() != null) {
                new ImageLoaderUtil(new ImageSize(90, 90), activity.getMyPhotoView(), userInfo.getPhoto(), activity).load();
            }
        }
        if (userInfo.getPhoto() != null) {
            new ImageLoaderUtil(new ImageSize(60, 60), register_photo, userInfo.getPhoto(), activity).load();
        }
        choose_photo = (Button) view.findViewById(R.id.choose_photo);
        upload_photo = (Button) view.findViewById(R.id.upload_photo);
        presenter = new UserInfoPresenterImpl(activity, this);
        dialog = new ProgressDialog(activity);
        dialog.setMessage("正在上传...");
        dialog.setCanceledOnTouchOutside(false);
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
            }
        });
        choose_photo.setOnClickListener(this);
        upload_photo.setOnClickListener(this);
    }

    @Override
    public void showDialog() {
        dialog.show();
    }

    @Override
    public void hideDialog() {
        dialog.hide();
        dialog.dismiss();
    }

    @Override
    public void showSuccess(String s, String upload_url) {
        if (upload_url != null) {
            url = upload_url;
        }
        Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void back() {
        getFragmentManager().popBackStack();
    }

    @Override
    public void showError(String error) {
        Toast.makeText(activity, "修改失败:" + error, Toast.LENGTH_SHORT).show();
    }

    private void choose() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            /**
             * 当选择的图片不为空的话，在获取到图片的途径
             */
            Uri uri = data.getData();
            Log.e("TAG", "uri = " + uri);
            try {
                String[] pojo = {MediaStore.Images.Media.DATA};

                Cursor cursor = activity.managedQuery(uri, pojo, null, null, null);
                if (cursor != null) {
                    ContentResolver cr = activity.getContentResolver();
                    int colunm_index = cursor
                            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(colunm_index);
                    /***
                     * 这里加这样一个判断主要是为了第三方的软件选择，比如：使用第三方的文件管理器的话，你选择的文件就不一定是图片了，
                     * 这样的话，我们判断文件的后缀名 如果是图片格式的话，那么才可以
                     */
                    if (path.endsWith("jpg") || path.endsWith("png")) {
                        photo = path;
                        Bitmap bitmap = BitmapFactory.decodeStream(cr
                                .openInputStream(uri));
                        register_photo.setImageBitmap(bitmap);
                    } else {
                        alert();
                    }
                } else {
                    alert();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void alert() {
        Dialog dialog = new AlertDialog.Builder(activity).setTitle("提示")
                .setMessage("您选择的不是有效的图片")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        photo = null;
                    }
                }).create();
        dialog.show();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choose_photo:
                choose();
                break;
            case R.id.upload_photo:
                if (photo != null) {
                    presenter.updatePhoto(photo, userInfo.getObjectId());
                } else {
                    showError("没有选择照片");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onBackPressed() {
        if (hadIntercept) {
            return false;
        } else {
            hadIntercept = true;
            return true;
        }
    }

}
